<!DOCTYPE html>
<html>
<head>
	<script type="text/javascript" src="js/d3.js"></script>
	<script type="text/javascript" src="js/d3.tip.js"></script>
	<script src="js/dojo-release-1.9.3/dojo/dojo.js"></script>
	<script type="text/javascript" src="js/nv.d3.js"></script>
	<link rel="stylesheet" type="text/css" href="css/nv.d3.css">
	<link rel="stylesheet" href="js/dojo-release-1.9.3/dojo/resources/dojo.css">
	<link rel="stylesheet" href="js/dojo-release-1.9.3/dijit/themes/claro/claro.css">
	<link rel="stylesheet" href="js/dojo-release-1.9.3/dojox/grid/resources/claroGrid.css">
	

	
	
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


<style>

.bar {
  fill: steelblue;
}

.bar2 {
  fill: orange;
}

.bar:hover {
  fill: brown;
}

.bar2:hover {
  fill: brown;
}


.axis {
  /*font: 10px sans-serif;*/
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.x.axis path {
  display: none;
}

.d3-tip {
  line-height: 1;
  /*font-weight: bold;*/
  padding: 12px;
  background: rgba(0, 0, 0, 0.4);
  color: #fff;
  border-radius: 2px;
}

/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
  box-sizing: border-box;
  display: inline;
  /*font-size: 10px;*/
  width: 100%;
  line-height: 1;
  color: rgba(0, 0, 0, 0.4);
  content: "\25BC";
  position: absolute;
  text-align: center;
}

/* Style northward tooltips differently */
.d3-tip.n:after {
  margin: -1px 0 0 0;
  top: 100%;
  left: 0;
}

#grid{
	margin-left: auto ;
	margin-right: auto ;
}

#test{
 	width: 900px ;
	margin-left: auto ;
	margin-right: auto ;
}

#sortMenu{
	border: 2px solid #a1a1a1;
	padding: 2px 2px;
    border-radius: 25px;
}

#circle {
    width: 50px;
    height: 50px;
    -webkit-border-radius: 25px;
    -moz-border-radius: 25px;
    border-radius: 25px; 
}

body{
 font-size:15px;
 font-family: Tahoma,sans-serif;
 color:black;
}


</style>

</head>

<body class="claro">
	<div style="font-size:20px;width:400px;margin-left:auto;margin-right:auto;">รายงานบุคลากร แยกตามประเภท</div>
	<div style="width:1000px;height:240px;margin-left: auto;margin-right: auto;margin-top: 10px;">
		<div style="display:inline-block;margin-left:5px;vertical-align:top;">
			<a href="index.html"><img src="images/home_icon.png"  width="50" height="50"></a>
		</div>
		<div style="display:inline-block;">
			<div id="grid" style="display:inline-block;"></div>
		</div>
	</div>
	<div id="test">
		<div id="sortMenu" style="width:450px;display:inline-block;float:left;">
			<span>เรียงลำดับโดย</span>
		    <input type="radio" name="sort" value="total" id="radio"> จำนวนบุคลากรทั้งหมด
		    <input type="radio" name="sort" value="male" id="radio"> บุคลากรชาย
		    <input type="radio" name="sort" value="female" id="radio">บุคลากรหญิง
		</div>
		<div style="display:inline-block;float:right;">
			<div style="background-color:steelblue;width:20px;height:20px;display:inline-block;"></div>
			<div style="display:inline-block;">ชาย</div>
			<div style="background-color:orange;width:20px;height:20px;display:inline-block;"></div>
			<div style="display:inline-block;">หญิง</div>
		</div>
		<div style="clear:both;"></div>
	</div>
</body>

	<script type="text/javascript">
	function genDonutChart(detailDatum){
		//create donutchart
		var donutChartSvg = d3.select("body").append("div").attr("id","detailChart").append("svg").attr("id","donutChart").attr("width","100%").attr("height","300px");
		
		nv.addGraph(function() {
		      var chart = nv.models.pieChart()
		          .x(function(d) { return d.label })
		          .y(function(d) { return d.value })
		          .showLabels(true)     //Display pie labels
		          .labelThreshold(.05)  //Configure the minimum slice size for labels to show up
		          .labelType("percent") //Configure what type of data to show in the label. Can be "key", "value" or "percent"
		          .donut(true)          //Turn on Donut mode. Makes pie chart look tasty!
		          .donutRatio(0.35);     //Configure how big you want the donut hole size to be.
		          

		        d3.selectAll("#donutChart")
		            .datum(detailDatum)
		            .transition().duration(350)
		            .call(chart);

		      return chart;
		}); 
	}
	function genDetailContent(detailData){
			
			require([
						"dojox/grid/DataGrid",
						"dojo/store/Memory",
						"dojo/data/ObjectStore",
						"dojo/request",
						"dijit/Dialog",
						"dojo/dom-construct",
						"dojo/domReady!"
					], function(DataGrid, Memory, ObjectStore, request,Dialog,domConstruct){
							var dialog = dijit.byId('dialog');
							if(!dialog){
								dialog = new Dialog({
							      id:'dialog',
							      //title:detailData[0].name,
							      onCancel: function(){
							    	  if(dojo.byId("detailChart")){
							    	  	dojo.byId("detailChart").remove();
							    	  }
						    	  },
							      style:'width:700px; height:auto;'
							    }); 
							}
							dialog.set("title",detailData[0].name);
							dialog.show();
							
							var grid = dijit.byId('dialogGrid')
							
							var dataStore =  new ObjectStore({ objectStore:new Memory({ data: detailData[1]}) });
							if(!grid){
								grid = new DataGrid({
								id:"dialogGrid",
								query: { id: "*" },
								structure: [
									{ name: "ลำดับ", field: "sequence", width: "50px" },
									{ name: "ชื่อ", field: "name", width: "250px" },
									{ name: "สังกัด", field: "depName", width: "330px" }
								],
								style:'width:680px;height:400px;'
								});
							}
						 var donutChart = dojo.byId("detailChart");
						 
						 if(donutChart){
							 domConstruct.place(donutChart, dialog.containerNode);
							 domConstruct.place(grid.domNode, donutChart,'after');
						 }else{
							 domConstruct.place(grid.domNode, dialog.containerNode,'first');
						 }
						 grid.setStore(dataStore);
						 grid.startup();
					});
	}
	
	function drilldown(p1,p2,p3){
		d3.json("FrmShowStaffByStaffTypeNow?criteria=depId&p1="+p1+"&p2="+p2+"&p3="+p3,function(error,data){
			genDonutChart(data[2]);
			genDetailContent(data);
		});
	}
	
	function drilldownBySex(p1,p2,p3){
		
		d3.json("FrmShowStaffByStaffTypeNow?criteria=depId&p1="+p1+"&p2="+p2+"&p3="+p3,function(error,data){
			genDetailContent(data);
		});
		
	}//end drilldownBySex
	
	var margin = {top: 20, right: 50, bottom: 100, left: 60},
    width = 800 - margin.left - margin.right,
    height = 600 - margin.top - margin.bottom; 
	var x = d3.scale.ordinal().rangeRoundBands([0, width], .1);
	
	var tip = d3.tip()
	  .attr('class', 'd3-tip')
	  .offset([-10, 0])
	  .html(function(d) {
	    return d.staffType+" ชาย : <span style='color:red'>" + d.maleStaffAmount + "</span>";
	  });
	
	var tip2 = d3.tip()
	  .attr('class', 'd3-tip')
	  .offset([-10, 0])
	  .html(function(d) {
	    return d.staffType+" หญิง: <span style='color:red'>" + d.femaleStaffAmount + "</span>";
	  });
	  
	d3.json("FrmShowStaffByStaffTypeNow",function(error,jsonData){	
		require([
					"dojox/grid/DataGrid",
					"dojo/store/Memory",
					"dojo/data/ObjectStore",
					"dojo/request",
					"dojo/domReady!"
				], function(DataGrid, Memory, ObjectStore, request){
					var grid, dataStore;
						dataStore =  new ObjectStore({ objectStore:new Memory({ data: jsonData}) });

						grid = new DataGrid({
							store: dataStore,
							query: { id: "*" },
							queryOptions: {},
							structure: [
								{ name: "ลำดับ", field: "sequence", width: "5%" },
								{ name: "ประเภทบุคลากร", field: "staffType", width: "30%" },
								{ name: "ชาย", field: "maleStaffAmount", width: "7%" ,styles: 'text-align: right;'},
								{ name: "หญิง", field: "femaleStaffAmount", width: "7%" ,styles: 'text-align: right;'},
								{ name: "รวม(คน)", field: "totalStaff", width: "10%" ,styles: 'text-align: right;'},
								{ name: "เปอร์เซ็นต์", field: "percenttage", width: "10%" ,styles: 'text-align: right;'
								,formatter: function(percenttage){return percenttage+"%";}}
							],
							style:'width:900px; height:220px;'
						}, "grid");
						grid.startup();
						
						var idx,itm,value;
						dojo.connect(grid, "onRowClick", grid, function(evt){
							idx = evt.rowIndex;
							item = this.getItem(idx);
							value = this.store.getValue(item,"staffTypeCode");
							drilldown("drilldown",'none',value);
						});
				});
			
		var y = d3.scale.linear().range([height, 0]);
		
		var xAxis = d3.svg.axis()
		    .scale(x)
		    .orient("bottom");
	
		var yAxis = d3.svg.axis()
		    .scale(y)
		    .orient("left")
		    .ticks(10);
		
		var svg = d3.select("#test").append("svg")
		    .attr("width", width + margin.left + margin.right)
		    .attr("height", height + margin.top + margin.bottom)
		    .append("g")
		    .attr("class","graph")
		    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
		
		svg.call(tip);
		svg.call(tip2);

	  x.domain(jsonData.map(function(d) { return d.staffType; }));
	  y.domain([0, d3.max(jsonData
	  , function(d) { 
		  if(d.maleStaffAmount > d.femaleStaffAmount){
			  return d.maleStaffAmount; 
		  }
		  else{
			  return d.femaleStaffAmount
		  }
	  })]);

	  svg.append("g")
	      .attr("class", "x axis")
	      .attr("transform", "translate(0," + height + ")")
	      .call(xAxis)
	      .selectAll("text")
	      .style("text-anchor","end")
	      .attr("transform",function(d){
	    	  return "translate(" +  this.getBBox().height + "," +
	    			  this.getBBox().height + ")rotate(-45)";
	      });

	  svg.append("g")
	      .attr("class", "y axis")
	      .attr("transform", "rotate(0)")
	      .call(yAxis)
	      .append("text")
	      .attr("y", -10)
	      .attr("dy", ".71em")
	      .style("text-anchor", "end")
	      .text("Amount");
	  
	  /* svg.append("g")
	  	  .attr("class", "y axis axisRight")
	      .attr("transform", "translate("+(width)+",0)")
	      .call(yAxis); */
	  
	  bars = svg.selectAll(".bar").data(jsonData).enter();
	  
	  bars.append("rect")
	      .attr("class", "bar")
	      .attr("x", function(d) { return x(d.staffType); })
	      .attr("width", x.rangeBand()/2)
	      .attr("y", function(d) { return y(d.maleStaffAmount); })
	      .attr("height", function(d) { return height - y(d.maleStaffAmount); })
	      .on('mouseover',tip.show)
	      .on('mouseout',tip.hide)
	  	  .on("click",function(d) {drilldownBySex("drilldownBySex","male",d.staffTypeCode)});
	  
	  bars.append("rect")
	      .attr("class", "bar2")
	      .attr("x", function(d) { return x(d.staffType) + x.rangeBand()/2; })
	      .attr("width", x.rangeBand()/2)
	      .attr("y", function(d) { return y(d.femaleStaffAmount); })
	      .attr("height", function(d) { 
	    	  return height - y(d.femaleStaffAmount); })
	      .on('mouseover',tip2.show)
	      .on('mouseout',tip2.hide)
	      .on("click",function(d) {drilldownBySex("drilldownBySex","female",d.staffTypeCode)});
	   	
	  d3.selectAll("#radio").on("change",function(){
		  change(this.value);
	  });
	 /*  d3.selectAll("input").on("change", function(){
		  alert(this.value);
	  }); */

	 /*  var sortTimeout = setTimeout(function() {
	  d3.select("input").property("checked", true).each(change);
	  }, 5000); */
		
		function change(sortType) {
		    //clearTimeout(sortTimeout);

		    // Copy-on-write since tweens are evaluated after a delay.
		    var x0;
		    if(sortType=="total"){
			    x0 = x.domain(jsonData.sort( function(a, b) { return b.totalStaff - a.totalStaff; })
		        .map(function(d) { return d.staffType; }))
		        .copy();
		    }
		    
		    else if(sortType=="male"){
			    x0 = x.domain(jsonData.sort( function(a, b) { return b.maleStaffAmount - a.maleStaffAmount; })
		        .map(function(d) { return d.staffType; }))
		        .copy();
		    }
		    
		    else if(sortType=="female"){
			    x0 = x.domain(jsonData.sort( function(a, b) { return b.femaleStaffAmount - a.femaleStaffAmount; })
		        .map(function(d) { return d.staffType; }))
		        .copy();
		    }
		    graphTransition(x0);
		    
		   /*  var x0 = x.domain(jsonData[1].sort(
		    		if(sortType=="total"){ 
		    			function(a, b) { return b.totalStaff - a.totalStaff; }
		    		}
		    		else if(sortType=="male"){
		    			function(a, b) { return b.maleStaffAmount, a.maleStaffAmount; }
		    		}
		    		else if(sortType=="female"){
		    			function(a, b) { return b.femaleStaffAmount, a.femaleStaffAmount; }
		    		}
		         )//end sortFunction
		        .map(function(d) { return d.staffType; }))
		        .copy(); */
		   function graphTransition(newX){

		    var transition = svg.transition().duration(750),
		        delay = function(d, i) { return i * 50; };

		    transition.selectAll(".bar")
		        .delay(delay)
		        .attr("x", function(d) { return newX(d.staffType); });
		    
		    transition.selectAll(".bar2")
	        .delay(delay)
	        .attr("x", function(d) { return newX(d.staffType)+ newX.rangeBand()/2; });

		    transition.select(".x.axis")
		        .call(xAxis)
		        .selectAll("g")
		        
		        /* .attr("transform",function(d){
		    	  return "rotate(-65)"
		        }) */
		        .selectAll("text")
		        .style("text-anchor","end")
		        .attr("transform",function(d){
	    	  			return "translate(" +  this.getBBox().height + "," +
	    			  	this.getBBox().height + ")rotate(-45)";
	      		})
		        .delay(delay);
		        //.style("text-anchor","end")
		        /* .attr("dx","-15")
		        .attr("dy","5"); */
		        /* .attr("transform",function(d){
			    	  return "translate(" +  this.getBBox().height * -2 + "," +
			    			  this.getBBox().height + ")rotate(-45)";
			    }); */
		       }
		    }//end change
	});
	</script>
</html>